<template>
  <div class="hold-transition">
    <div id="app" style="width: 85vw;">
      <div class="content-header">
        <h1>旅客管理<small>旅客信息</small></h1>
        <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>旅客管理</el-breadcrumb-item>
          <el-breadcrumb-item>旅客信息</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <div class="app-container">
        <div class="box">
          <!-- 搜索和操作按钮 -->
          <div class="filter-container">
            <el-input
              placeholder="姓名/身份证号"
              v-model="pagination.queryString"
              style="width: 200px;"
              class="filter-item"
            ></el-input>
            <el-button @click="findPage()" class="dalfBut">查询</el-button>
            <el-button type="primary" class="butT" @click="handleCreate()">新建</el-button>
          </div>

          <!-- 数据表格 -->
          <el-table
            v-loading="loading"
            size="small"
            current-row-key="passengerId"
            :data="dataList"
            stripe
            highlight-current-row
          >
            <el-table-column type="index" align="center" label="序号"></el-table-column>
            <el-table-column prop="name" label="姓名" align="center"></el-table-column>
            <el-table-column prop="gender" label="性别" align="center"></el-table-column>
            <el-table-column prop="age" label="年龄" align="center"></el-table-column>
            <el-table-column prop="idCardNumber" label="身份证号" align="center"></el-table-column>
            <el-table-column prop="phoneNumber" label="手机号" align="center"></el-table-column>
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页组件 -->
          <div class="pagination-container">
            <el-pagination
              class="pagiantion"
              @current-change="findPage"
              :current-page="pagination.currentPage"
              :page-size="pagination.pageSize"
              :total="pagination.total"
              layout="total, prev, pager, next, jumper"
            ></el-pagination>
          </div>

          <!-- 新增旅客弹层 -->
          <el-dialog title="新增旅客" v-model="dialogFormVisible">
            <el-form
              ref="dataAddForm"
              :model="formData"
              :rules="rules"
              label-position="right"
              label-width="100px"
            >
              <el-row>
                <el-col :span="12">
                  <el-form-item label="姓名" prop="name">
                    <el-input v-model="formData.name"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="性别" prop="gender">
                    <el-select v-model="formData.gender">
                      <el-option label="男" value="男"></el-option>
                      <el-option label="女" value="女"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="年龄" prop="age">
                    <el-input v-model.number="formData.age" type="number"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="身份证号" prop="idCardNumber">
                    <el-input v-model="formData.idCardNumber"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="手机号" prop="phoneNumber">
                    <el-input v-model="formData.phoneNumber"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="handleAdd()">确定</el-button>
              </span>
            </template>
          </el-dialog>

          <!-- 编辑旅客弹层 -->
          <el-dialog title="编辑旅客" v-model="dialogFormVisible4Edit">
            <el-form
              ref="dataEditForm"
              :model="formData"
              :rules="rules"
              label-position="right"
              label-width="100px"
            >
              <el-row>
                <el-col :span="12">
                  <el-form-item label="姓名" prop="name">
                    <el-input v-model="formData.name"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="性别" prop="gender">
                    <el-select v-model="formData.gender">
                      <el-option label="男" value="男"></el-option>
                      <el-option label="女" value="女"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="年龄" prop="age">
                    <el-input v-model.number="formData.age" type="number"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="身份证号" prop="idCardNumber">
                    <el-input v-model="formData.idCardNumber"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="手机号" prop="phoneNumber">
                    <el-input v-model="formData.phoneNumber"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="dialogFormVisible4Edit = false">取消</el-button>
                <el-button type="primary" @click="handleEdit()">确定</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import service from '@/util/http';

// 表单引用
const dataAddForm = ref(null);
const dataEditForm = ref(null);
const loading = ref(false);

// 数据列表
const dataList = ref([]);

// 表单数据
const formData = reactive({
  passengerId: null,
  name: '',
  gender: '',
  age: null,
  idCardNumber: '',
  phoneNumber: ''
});

// 对话框显示控制
const dialogFormVisible = ref(false);
const dialogFormVisible4Edit = ref(false);

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  queryString: ''
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '姓名为必填项', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在2-20个字符之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '性别为必选项', trigger: 'change' }
  ],
  age: [
    { required: true, message: '年龄为必填项', trigger: 'blur' },
    { type: 'number', min: 0, max: 150, message: '年龄必须在0-150之间', trigger: 'blur' }
  ],
  idCardNumber: [
    { required: true, message: '身份证号为必填项', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '手机号为必填项', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
};

// 分页查询
const findPage = async (page = 1) => {
  loading.value = true;
  try {
    pagination.currentPage = page;
    const params = {
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize,
      queryString: pagination.queryString
    };
    const response = await service.get('/admin/passenger/page', { params });
    if (response.data.flag) {
      pagination.total = response.data.data.total;
      dataList.value = response.data.data.records;
    } else {
      ElMessage.error(response.data.message || '查询失败');
    }
  } catch (error) {
    console.error('查询失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    passengerId: null,
    name: '',
    gender: '',
    age: null,
    idCardNumber: '',
    phoneNumber: ''
  });
  // 重置表单验证
  if (dataAddForm.value) dataAddForm.value.resetFields();
  if (dataEditForm.value) dataEditForm.value.resetFields();
};

// 新建按钮处理
const handleCreate = () => {
  resetForm();
  dialogFormVisible.value = true;
};

// 添加旅客
const handleAdd = () => {
  dataAddForm.value?.validate(async (valid) => {
    if (valid) {
      try {
        dialogFormVisible.value = false;
        const response = await service.post('/admin/passenger', formData);
        if (response.data.flag) {
          ElMessage.success(response.data.message);
          findPage();
        } else {
          ElMessage.error(response.data.message);
        }
      } catch (error) {
        console.error('添加失败:', error);
        ElMessage.error('添加失败');
      }
    }
  });
};

// 编辑按钮处理
const handleUpdate = async (row) => {
  try {
    const response = await service.get(`/admin/passenger/${row.passengerId}`);
    if (response.data.flag) {
      Object.assign(formData, response.data.data);
      dialogFormVisible4Edit.value = true;
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    console.error('获取详情失败:', error);
    ElMessage.error('获取详情失败');
  }
};

// 提交编辑
const handleEdit = () => {
  dataEditForm.value?.validate(async (valid) => {
    if (valid) {
      try {
        dialogFormVisible4Edit.value = false;
        const response = await service.put(`/admin/passenger/${formData.passengerId}`, formData);
        if (response.data.flag) {
          ElMessage.success(response.data.message);
          findPage();
        } else {
          ElMessage.error(response.data.message);
        }
      } catch (error) {
        console.error('更新失败:', error);
        ElMessage.error('更新失败');
      }
    }
  });
};

// 删除旅客
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该旅客信息吗？', '提示', { type: 'warning' })
    .then(async () => {
      try {
        const response = await service.delete(`/admin/passenger/${row.passengerId}`);
        if (response.data.flag) {
          ElMessage.success(response.data.message);
          findPage();
        } else {
          ElMessage.error(response.data.message);
        }
      } catch (error) {
        console.error('删除失败:', error);
        ElMessage.error('删除失败');
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除操作');
    });
};

// 页面加载时执行查询
onMounted(() => {
  findPage();
});
</script>

<style scoped>
@import '../css/style.css';
</style>